package com.viewshine.nettydemo.staticMethod.nettyServer;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName BasicsEchoServerHandler
 * @Author rhb
 * @Description 基础/静态 服务端处理器
 * @Date 2019-01-17 14:21
 * @Version 1.0
 **/
@ChannelHandler.Sharable
@Slf4j
public class BasicsEchoServerHandler extends ChannelHandlerAdapter {


    /**
     * 有客户端连接上
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.debug("channelActive");
    }


    /**
     * 当从Channel中读数据时被调用
     *
     * @param ctx
     * @param msg 数据内容
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //收到数据
        log.debug("channelRead");
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "UTF-8");
        log.debug("The time server receive order : " + body);
//        ctx.writeAndFlush(body);

        Map map = new HashMap();
        map.put("aha", 101);
        map.put("cc", "来福");
        map.put("age", 12L);
        String json = JSON.toJSONString(map);
        ByteBuf resp = Unpooled.copiedBuffer(json.getBytes());
        ctx.write(resp);//写回数据
    }


    /**
     * 当Channel上的某个读操作完成时被调用
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) //flush掉所有写回的数据
                .addListener(ChannelFutureListener.CLOSE); //当flush完成后关闭channel
    }


    /**
     * 异常捕获
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        try {
            cause.printStackTrace();
        } finally {
            ctx.close();
        }
    }


}
